package com.xinwei.leetcode.数组;

import java.util.TreeSet;

// https://leetcode-cn.com/problems/third-maximum-number/
public class _414_第三大的数 {
    // 有序集合
    // first 为有序集合中最小的数，last 为最大的数
    public int thirdMax(int[] nums) {
        TreeSet<Integer> set = new TreeSet<>();
        for (int num : nums) {
            set.add(num);
            if (set.size() > 3) {
                set.remove(set.first());
            }
        }
        return (set.size() == 3) ? set.first() : set.last();
    }

    // 设置三个变量模拟有序数组
    public int thirdMax1(int[] nums) {
        long a = Long.MIN_VALUE; // 模拟最大值
        long b = Long.MIN_VALUE; // 模拟第二大值
        long c = Long.MIN_VALUE; // 模拟第三大值
        for (int num : nums) {
            if (num > a) {
                c = b;
                b = a;
                a = num;
            }else if (num > b && num < a) {
                c = b;
                b = num;
            }else if (num < b && num > c) {
                c = num;
            }
        }
        return  (c == Long.MIN_VALUE) ? (int) a : (int) c;
    }
}
